#include <vector>
#include <memory>
#include <cstdint>
#include <cstddef>
#include <iostream>
#include <new>
 
template<typename T>
class SimpleMemoryPool {
public:
    SimpleMemoryPool(size_t initial_capacity) {
        capacity_ = initial_capacity;
        pool_.resize(initial_capacity * sizeof(T));
        free_list_.reserve(initial_capacity);
        for (size_t i = 0; i < initial_capacity; ++i) {
            free_list_.push_back(reinterpret_cast<T*>(&pool_[i * sizeof(T)]));
        }
    }
 
    ~SimpleMemoryPool() {
        // 析构时释放所有对象，防止内存泄漏
        for (auto obj : free_list_) {
            obj->~T(); // 显式调用析构函数，但不释放内存
        }
    }
 
    T* allocate() {
        if (!free_list_.empty()) {
            T* obj = free_list_.back();
            free_list_.pop_back();
            return obj;
        } else {
            return nullptr; // 或抛出异常，表示内存池已满
        }
    }
 
    void deallocate(T* obj) {
        obj->~T(); // 显式调用析构函数，但不释放内存
        free_list_.push_back(obj); // 归还到空闲列表
    }
 
private:
    std::vector<char> pool_; // 存储所有对象的内存池
    std::vector<T*> free_list_; // 空闲对象列表
    size_t capacity_; // 容量大小
};

struct MyObject {
    MyObject() { std::cout << "Object created\n"; }
    ~MyObject() { std::cout << "Object destroyed\n"; }
};
 
int main() {
    SimpleMemoryPool<MyObject> pool(10); // 创建一个初始容量为10的内存池
    MyObject* obj = pool.allocate(); // 分配一个对象
    pool.deallocate(obj); // 释放对象回到池中
}